package org.example.http;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import static org.example.constant.Common.EMPTY_URL;
import static org.example.constant.Common.MAP_URL;

public class HttpUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final OkHttpClient client =  new OkHttpClient.Builder()
            .connectTimeout(300, java.util.concurrent.TimeUnit.SECONDS)    // 连接超时
            .readTimeout(600, java.util.concurrent.TimeUnit.SECONDS)       // 读取超时
            .writeTimeout(600, java.util.concurrent.TimeUnit.SECONDS)      // 写入超时
            .build();;
    public static String httpPostQueryMap(ParamEntity paramEntity) throws Exception {

        String requestBody = objectMapper.writeValueAsString(paramEntity);
        System.out.println("请求参数: " );
        //java发起http post请求，解析返回值
        String result=sendPostRequest(MAP_URL,requestBody);
        // 记录返回值
        System.out.println("返回结果: " );



        Result resultEntity=objectMapper.readValue(result,Result.class);
        if(resultEntity!=null&&resultEntity.getCode().equals("200")){
            return resultEntity.getData().getImgUrl();
        }else {
            return EMPTY_URL;
        }
    }
    /**
     * 发起HTTP POST请求并解析返回值
     * @param urlString 请求URL
     * @return 响应结果字符串
     * @throws Exception 网络请求异常
     */
    public static String sendPostRequest(String urlString, String json) throws Exception {

        int maxRetries = 3;  // 最大重试次数
        Exception lastException = null;

        for (int i = 0; i < maxRetries; i++) {
            try {
                long startTime = System.currentTimeMillis();
                System.out.println(json);

                RequestBody requestBody = RequestBody.create(
                        json,
                        MediaType.parse("application/json; charset=utf-8")
                );

                Request request = new Request.Builder()
                        .url(urlString)
                        .post(requestBody)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        System.out.println("JSON 提交成功，响应: ");
                        return response.body().string();
                    } else {
                        throw new Exception("HTTP POST 请求失败，状态码: " + response.code());
                    }
                }
            } catch (IOException e) {
                lastException = e;
                System.out.println("第 " + (i + 1) + " 次请求失败，准备重试...");
                if (i < maxRetries - 1) {
                    Thread.sleep(1000 * (i + 1)); // 递增延迟重试
                }
            }
        }

        throw new Exception("请求重试 " + maxRetries + " 次后仍然失败", lastException);
    }


}
